#include "Thread.hpp"
#include <unistd.h>
#include <vector>

static pthread_mutex_t mutex;
std::string GetThreadname()
{
    static int num = 1;
    char name[64];
    snprintf(name, sizeof(name), "Thread-%d", num);
    num ++;
    return (const char*)name;
}
void Print(int num)
{
    while(num --)
    {
        std::cout << "Helloworld-" << num << std::endl;
        sleep(1);
    }
}
static int ticket = 10000;
void BuyTicket(pthread_mutex_t* mutex)
{
    while(true)
    {
        pthread_mutex_lock(mutex);
        if(ticket > 0)
        {
            usleep(1000);
            std::cout << "getTicket:" << ticket << std::endl;
            ticket--;
            pthread_mutex_unlock(mutex);

        }
        else
        {
            pthread_mutex_unlock(mutex);
            break;
        }
    };
}
int main()
{
    pthread_mutex_init(&mutex, nullptr);
    Thread<pthread_mutex_t*> t(GetThreadname(), BuyTicket, &mutex);

    t.Start();
    
    t.Join();
    const int num = 5;
    std::vector<Thread<pthread_mutex_t*>> threads;
    for(int i = 0;i < num;i ++)
    {
        threads.push_back(Thread<pthread_mutex_t*>(GetThreadname(), BuyTicket, &mutex));
    }

    for(int i = 0;i < 5;i ++)
    {
        threads[i].Start();
    }

    for(int i = 0;i < 5;i ++)
    {
        threads[i].Join();
    }
    return 0;
}